import xbmc
import telnetlib, time, sys
import json
import threading
from xbmcEvents import EventHandler

"""

Class is heavily based off of the class made by the people working on the Trakt Utilities Add-on
https://github.com/Manromen/script.TraktUtilities/wiki
(Thank you)

"""

# Receives XBMC notifications and passes them off
class NotificationService(threading.Thread):
    def __init__(self, debug=False):
        self.debug = debug
        self.abortRequested = False
        self.events = EventHandler()
    
    # Method that monitors the xbmc jsonrpc service for events
    # Method mostly a copy and paste from the Trakt Utilities
    # addon credits are above.
    def run(self):        
        #while xbmc is running        
        while (not (self.abortRequested or xbmc.abortRequested)):
            try:
                tn = telnetlib.Telnet('localhost', 9090, 10)
            except IOError as (errno, strerror):
                #connection failed, try again soon
                if self.debug:
                    print "[Notification Service] Telnet too soon? ("+str(errno)+") "+strerror
                time.sleep(1)
                continue
            
            if self.debug:
                print "[Notification Service] Waiting~"
            bCount = 0
            
            while (not (self.abortRequested or xbmc.abortRequested)):
                try:
                    if bCount == 0:
                        notification = ""
                        inString = False
                    [index, match, raw] = tn.expect(["(\\\\)|(\\\")|[{\"}]"], 0.2) #note, pre-compiled regex might be faster here
                    notification += raw
                    if index == -1: # Timeout
                        continue
                    if index == 0: # Found escaped quote
                        match = match.group(0)
                        if match == "\"":
                            inString = not inString
                            continue
                        if match == "{":
                            bCount += 1
                        if match == "}":
                            bCount -= 1
                    if bCount > 0:
                        continue
                    if bCount < 0:
                        bCount = 0
                except EOFError:
                    break #go out to the other loop to restart the connection
                
                if self.debug:
                    print "[Notification Service] message: " + str(notification)
                
                # Parse recieved notification
                data = json.loads(notification)
                
                # Checks event type and routes to handler
                if 'method' in data and 'params' in data and 'sender' in data['params'] and data['params']['sender'] == 'xbmc':
                    if data['method'] == 'System.OnQuit':
                        self.abortRequested = True
                    self.events.event(data)
                    
                
            time.sleep(1)
        tn.close()
        self.events.follwitAddon.follwitAPI.close()
        print '[Notification Service] message: stopping notification service'
        
    
